package com.xbongbong.paas.connection.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.connection.connector.service.AbstractStandardConnector;
import com.xbongbong.paas.connection.connector.service.StandardConnectorFactory;
import com.xbongbong.paas.connection.pojo.connector.ActionBasePojo;
import com.xbongbong.paas.connection.service.IOpenAppService;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

/**
 * 连接器执行动作
 */
@Component
public class DdConnectorService implements IOpenAppService {

    private static final Logger LOG = LoggerFactory.getLogger(DdConnectorService.class);

    @Resource
    private StandardConnectorFactory standardConnectorFactory;
    @Resource
    private MongoLogHelp mongoLogHelp;

    @Override
    public JSONObject getHeader() {
        return null;
    }

    @Override
    public void dataInit(String corpid) throws XbbException {

    }

    @Override
    public JSONObject dataInitSchedule() {
        return null;
    }

    @Override
    public BaseVO openAppApiCallbackAccept(JSONObject jsonObject) throws XbbException {
        LOG.info("openAppApiCallbackAccept jsonObject:" + jsonObject);
        TransmittableThreadLocalUtil.setConnectorValue();
        String modelId = jsonObject.getString("ddDataModelId");
        AbstractStandardConnector standardConnector = standardConnectorFactory.getStandardConnector(modelId);
        if (Objects.isNull(standardConnector)) {
            LOG.warn("modelId不在处理范围内，modelId：" + modelId);
        }
        try {
            ActionBasePojo actionBasePojo = jsonObject.toJavaObject(ActionBasePojo.class);
            String corpid = actionBasePojo.getDdDataCorpId();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_RECEIVE_DATA_FROM_CONNECTOR), JSON.toJSONString(jsonObject));
            mongoLogHelp.buildLog(corpid, "system", "系统", OperateModuleTypeEnum.CONNECTOR, OperateTypeEnum.RECEIVE_DATA_CONNECTOR,
                    "", "连接器", memo, null);
        } catch (Exception e) {
            LOG.error("接收连接器数据的日志记录失败！", e);
        }
        standardConnector.action(jsonObject);
        return new BaseVO();
    }
    @Override
    public void requestCheck(HttpServletRequest httpRequest, JSONObject data) throws XbbException {
        //钉钉连接器消息发送方变更，这个验证弃用
//        String body = data.toString();
//        boolean isLegal = SignatureVerify.verify(buildUrlWithQueryString(httpRequest),
//                getHeaders(httpRequest), body.getBytes());
//        LOG.info("isLegal:" + isLegal);
//        if (!isLegal) {
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028.getCode(), "钉钉签名校验失败");
//        }
    }

    public String buildUrlWithQueryString(HttpServletRequest request) {
        if (StringUtil.isEmpty(request.getQueryString())) {
            return request.getRequestURL().toString();
        } else {
            return request.getRequestURL() + "?" + request.getQueryString();
        }
    }

    public List<Header> getHeaders(HttpServletRequest request) {
        List<Header> headerList = new ArrayList<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String)headerNames.nextElement();
            String value = request.getHeader(key);
            headerList.add(new BasicHeader(key, value));
        }
        return headerList;
    }
}
